var express = require('express');
var router = express.Router();
var pgclient = require('dao/pgHelper')
pgclient.getConnection();
var cors = require('cors');
	router.use(cors());

/* GET home page. */
router.get('/', function(req, res, next) {
  if(req.cookies.islogin){
          req.session.islogin=req.cookies.islogin;
      }
  	if(req.session.islogin){
  	    res.locals.islogin=req.session.islogin;
  	}
    	res.render('index', { title: 'HOME',test:res.locals.islogin});
});

/* GET login page. */
router.route('/login')
	.get(function(req, res) {
	     if(req.session.islogin){
			res.locals.islogin=req.session.islogin;
		}

		if(req.cookies.islogin){
			req.session.islogin=req.cookies.islogin;
		}
		res.render('login', { title: '用户登录' ,test:res.locals.islogin});
	})
	.post(function(req,res){
		result=null;
		var username = req.body.inputUsername;
		console.log('用户名：',username);
		var password = req.body.inputPassword;
		//调用数据库管理类中的查询语句，参数是表名、用户名
		pgclient.select('userinfo',{'username': username},'', function (result){
			if(result[0]===undefined){
				res.send('没有该用户');
			}else{
				if(result[0].password===password){
					req.session.islogin=username;
					res.locals.islogin=req.session.islogin;
					res.cookie('islogin',res.locals.islogin,{maxAge:60000});
					res.redirect('/');
				}else
				{
					res.redirect('/login');
				}
			}
	});
});

router.route('/reg')
    .get(function(req,res){
        res.render('reg',{title:'注册'});
    })
    .post(function(req,res) {
        //调用数据库管理类中的写入语句，参数是表名userinfo，username、password、emal、telephone
		console.log(req.body.inputUsername,'---',req.body.inputPasswordConfirm,'---',req.body.inputEmail,'---',req.body.inputTelephone);
		pgclient.save('userinfo',{'username': req.body.inputUsername,'password': req.body.inputPasswordConfirm,'email': req.body.inputEmail,'telephone': req.body.inputTelephone}, function (err) {
			pgclient.select('userinfo',{'username': req.body.inputUsername},'', function (result) {
				if(result[0]===undefined){
					res.send('注册没有成功，请重新注册');
				}else{
					//res.send('注册成功！');
					res.redirect('/login');
				}
			}); 
		});	
	});

router.get('/logout', function(req, res) {
    res.clearCookie('islogin');
    req.session.destroy();
    res.redirect('/');
});

//添加关联字段查询省GDP表的路由
router.get('/GDPQuery', function(req, res) {
    var code = req.query.code;
    console.log('路由中的code::::::'+code);
	pgclient.selectpolygon_gdpByCode('polygon_gdp', code,'', function(result) {
		if(result[0] === undefined) {
			res.send('返回空值');
		} else {
            res.send(result);
			console.log("返回结果：" + JSON.stringify(result))
		}
	});
});

module.exports = router;
